"""
股票搜索服务模块
提供股票代码搜索和联想功能 - 使用yfinance Search
"""
import yfinance as yf
import pandas as pd
import time
import random
from typing import List, Dict, Any, Optional
from config import Config


class SearchService:
    """股票搜索服务类"""

    @staticmethod
    def search_stocks(query: str, limit: int = 10) -> List[Dict[str, Any]]:
        """
        使用yfinance搜索股票代码和名称

        Args:
            query: 搜索查询词
            limit: 返回结果数量限制

        Returns:
            匹配的股票列表
        """
        if not query or len(query.strip()) < 1:
            return []

        query = query.strip()
        results = []

        try:
            # 使用yfinance的Search功能
            search_result = yf.Search(query)
            print(search_result)
            if hasattr(search_result, 'quotes') and search_result.quotes:
                # 提取搜索结果中的股票信息
                for quote in search_result.quotes[:limit]:
                    print(quote)
                    if 'symbol'in quote and 'longname' in quote and 'exchange' in quote and 'sector' in quote:
                        results.append({
                            'symbol': quote["symbol"],
                            'name': quote["longname"],
                            'sector': quote["sector"],
                            'exchange': quote["exchange"]
                        })
            print(f"yfinance搜索结果: {results}")
        except Exception as e:
            print(f"yfinance搜索失败: {str(e)}")
            return []

        return results

    